/**
 * 
 */
package com.wistech.search.solr.extend;

import java.io.IOException;
import java.util.Collection;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

import com.google.common.collect.Sets;
import com.wistech.commons.utils.spring.SpringContextHolder;

/**
 * 在线状态过滤器
 * 
 * @author Liuye
 * 
 */
@SuppressWarnings("serial")
public class OnlineFilter extends Filter {
	public static final String FIELD_NAME = "live_online";
	private static final String KEY = "companyId";

	private Collection<String> onlineCompanyIds = Sets.newHashSet();

	public OnlineFilter() {
		ExternalDataContext context = SpringContextHolder
				.getBean("externalDataContext");
		onlineCompanyIds.addAll(context.getOnlineCompanyIds());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.
	 * IndexReader)
	 */
	@Override
	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
		if (onlineCompanyIds == null || onlineCompanyIds.isEmpty()) {
			return new OpenBitSet();
		}
		FieldCache.StringIndex companyIdIndex = FieldCache.DEFAULT
				.getStringIndex(reader, KEY);
		OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());
		for (int i = 0; i < reader.maxDoc(); i++) {
			if (reader.isDeleted(i))
				continue;
			String companyId = getCompanyId(companyIdIndex, i);
			if (companyId != null && onlineCompanyIds.contains(companyId)) {
				bitSet.fastSet(i);
			}
		}
		return bitSet;
	}

	private String getCompanyId(FieldCache.StringIndex index, int doc) {
		final int ord = index.order[doc];
		return ord == 0 ? null : index.lookup[ord];
	}
}
